﻿using MHI.ScenarioManager.Data;
using MHI.ScenarioManager.Interfaces;
using WebFoundation;
using WebFoundation.Data;
using WebFoundation.GenericModules;
using WebFoundation.GenericModules.Interfaces;
using WebFoundation.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MHI.ScenarioManager.Business
{
    internal class ScenarioGroupList : GroupList<Scenario,IScenarioList>,IScenarioGroupList
    {
        public static GroupTypes ScenarioGroupType = new GroupTypes("Scenario");

        private DbManager _db = null;
        private IScenarioList _scenarioList = null;
        private WFModule _module;

        public ScenarioGroupList(DbManager db, IScenarioList list, WFModule module)
            : base(ScenarioGroupType, db, list, module,true)
        {
            _db = db;
            _scenarioList = list;
            _module = module;
        }

        public Group CreateRootScenarioGroup(string groupName)
        {
            return this.AddGroup((Group)null, groupName);
        }

        public Group CreateScenarioGroup(Group parent,string groupName)
        {
            return this.AddGroup(parent, groupName);
        }

        public Group CreateScenarioGroupLinkScenario(Group parent, Scenario scenario)
        {
            GroupItem<Scenario> item = this.AddItem(parent, scenario);
            return item as Group;
        }

        public List<Group> GetRootScenarioGroups()
        {
            return this.GetRootGroups().Where(r => r.GroupType == ScenarioGroupType.Id).ToList<Group>();
        }

        public List<Group> GetScenarioGroupsByGroup(Group parent)
        {
            return this.GetAllSubGroups(parent).Where(r=>r.ItemRef == null).ToList<Group>();
        }

        public List<Scenario> GetScenariosByGroup(Group group)
        {
            List<Scenario> scenarios = new List<Scenario>();
            GroupItem<Scenario>[] items = this.GetChildrenGroupItems(group);
            for (int index = 0; index < items.Length;index++)
            {
                GroupItem<Scenario> item = items[index];
                Scenario scenario = item.Data;
                if (scenario == null)
                {
                    continue;
                }
                if (scenario.Template != 1)
                {
                    scenarios.Add(item.Data);
                }
            }
            return scenarios;
        }

        public Group GetGroupByScenario(Scenario scenario)
        {
            Group group = null;
            Group[] groups = this.GetGroupsByItemId(scenario);
            if(groups!=null && groups.Length>0)
            {
                group = groups[0];
            }
            return group;
        }

        public bool DeleteScenario(Scenario scenario)
        {
            return this.DeleteGroupItem(scenario.Id,true);
        }

    }
}
